<template>
  <div class="widget-form-container">
    <div v-if="!widgetForm.list.length" class="form-empty">从左侧拖拽来添加字段</div>
    <a-form
      layout="vertical"
      :label-align="widgetForm.config.labelAlign"
      :label-col="widgetForm.config.labelCol"
      :hide-required-mark="widgetForm.config.hideRequiredMark"
      class="widget-form"
    >
      <Draggable
        class="widget-form-list ant-row"
        item-key="key"
        ghost-class="ghost"
        handle=".drag-widget"
        :animation="200"
        :group="{ name: 'people' }"
        :list="widgetForm.list"
        @add="handleMoveAdd"
      >
        <template #item="{ element, index }">
          <a-col :span="element.options.gridLayoutNumber" style="padding-left: 8px; padding-right: 8px">
            <transition-group name="fade" tag="div">
              <template v-if="element.type === 'grid'">
                <div v-for="(item, i) in element.columns" :key="i">
                  <a-row
                    v-if="element.key"
                    :key="element.key"
                    class="widget-col widget-view"
                    type="flex"
                    :class="{ active: widgetFormSelect?.key === element.key }"
                    :gutter="element.options.gutter ?? 0"
                    :justify="element.options.justify"
                    :align="element.options.align"
                    @click="handleItemClick(element)"
                  >
                    <a-col v-for="(col, colIndex) of item" :key="colIndex" :span="col.gridLayoutNumber ?? 0">
                      <Draggable
                        class="widget-col-list"
                        item-key="key"
                        ghost-class="ghost"
                        handle=".drag-widget"
                        :animation="200"
                        :group="{ name: 'people' }"
                        :no-transition-on-drag="true"
                        :list="col.list"
                        @add="handleColMoveAdd($event, element, colIndex)"
                      >
                        <template #item="{ element: el, index: _index }">
                          <transition-group name="fade" tag="div">
                            <AntdWidgetFormItem
                              v-if="el.key"
                              :key="el.key"
                              :element="el"
                              :config="widgetForm.config"
                              :select-widget="widgetFormSelect"
                              @click.stop="handleItemClick(el)"
                              @copy="handleCopyClick(_index, col.list)"
                              @delete="handleDeleteClick(_index, col.list)"
                            />
                          </transition-group>
                        </template>
                      </Draggable>
                    </a-col>
                    <div v-if="widgetFormSelect?.key === element.key" class="widget-view-action widget-col-action">
                      <SvgIcon
                        name="delete"
                        prefix="icon-form"
                        @click.stop="handleDeleteClick(index, widgetForm.list)"
                      />
                    </div>

                    <div v-if="widgetFormSelect?.key === element.key" class="widget-view-drag widget-col-drag">
                      <SvgIcon name="move" prefix="icon-form" class="drag-widget" />
                    </div>
                  </a-row>
                </div>
              </template>
              <template v-else-if="element.type === 'fixedCombination'">
                <FixedCombination
                  :element="element"
                  :config="widgetForm.config"
                  :select-widget="widgetFormSelect"
                  @click="handleItemClick(element)"
                  @delete="handleDeleteClick(index, widgetForm.list)"
                />
              </template>
              <template v-else-if="element.type === 'packing'">
                <packing-design
                  :element="element"
                  :config="widgetForm.config"
                  :select-widget="widgetFormSelect"
                  @click="handleItemClick(element)"
                  @delete="handleDeleteClick(index, widgetForm.list)"
                ></packing-design>
              </template>
              <template v-else>
                <AntdWidgetFormItem
                  v-if="element.key"
                  :key="element.key"
                  :element="element"
                  :config="widgetForm.config"
                  :select-widget="widgetFormSelect"
                  @click="handleItemClick(element)"
                  @copy="handleCopyClick(index, widgetForm.list)"
                  @delete="handleDeleteClick(index, widgetForm.list)"
                />
              </template>
            </transition-group>
          </a-col>
        </template>
      </Draggable>
    </a-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, nextTick, PropType } from 'vue'
import Draggable from 'vuedraggable'
import { v4 } from 'uuid'
// import { randomRange } from '@/utils/index'
import AntdWidgetFormItem from './AntdWidgetFormItem.vue'
import FixedCombination from './FixedCombination.vue'
// import SvgIcon from '@/components/SvgIcon.vue'
import { WidgetForm } from '@@/enums/customFormEnums'
import { cloneDeep } from 'lodash'
import PackingDesign from './packingDesign/index.vue'

const handleListInsert = (key: string, list: any[], obj: any) => {
  const newList: any[] = []
  list.forEach((item) => {
    if (item.key === key) {
      newList.push(item)
      newList.push(obj)
    } else {
      if (item.columns) {
        item.columns = item.columns.map((col: any) => ({
          ...col,
          list: handleListInsert(key, col.list, obj)
        }))
      }
      newList.push(item)
    }
  })
  return newList
}

const handleListDelete = (key: string, list: any[]) => {
  const newList: any[] = []
  list.forEach((item) => {
    if (item.key !== key) {
      if (item.columns && item.columns[0]) {
        item.columns[0] = item.columns[0].map((col: any) => ({
          ...col,
          list: handleListDelete(key, col.list)
        }))
      }
      newList.push(item)
    }
  })
  return newList
}

export default defineComponent({
  name: 'AntdWidgetForm',
  components: {
    // SvgIcon,
    Draggable,
    AntdWidgetFormItem,
    FixedCombination,
    PackingDesign
  },
  props: {
    widgetForm: {
      type: Object as PropType<WidgetForm>,
      required: true
    },
    widgetFormSelect: {
      type: Object
    }
  },
  emits: ['update:widgetForm', 'update:widgetFormSelect', 'itemClick'],
  setup(props, context) {
    // 点击选中组件
    const handleItemClick = (row: any) => {
      context.emit('update:widgetFormSelect', row)
      context.emit('itemClick')
    }
    // 复制组件
    const handleCopyClick = (index: number, list: any[]) => {
      const key = v4().replaceAll('-', '')
      const oldList = cloneDeep(props.widgetForm.list)
      let copyData = {
        ...list[index],
        key,
        model: `${key}`,
        rules: list[index].rules ?? []
      }

      if (list[index].type === 'radio' || list[index].type === 'checkbox' || list[index].type === 'select') {
        copyData = {
          ...copyData,
          options: {
            ...copyData.options,
            options: copyData.options.options.map((item: any) => ({ ...item }))
          }
        }
      }

      context.emit('update:widgetForm', {
        ...props.widgetForm,
        list: handleListInsert(list[index].key, oldList, copyData)
      })

      context.emit('update:widgetFormSelect', copyData)
    }

    // 删除组件
    const handleDeleteClick = (index: number, list: any[]) => {
      const oldList = cloneDeep(props.widgetForm.list)
      const deleteFieldIds = cloneDeep(props.widgetForm.deleteFieldIds)

      if (list.length - 1 === index) {
        if (index === 0) {
          nextTick(() => context.emit('update:widgetFormSelect', null))
        } else {
          context.emit('update:widgetFormSelect', list[index - 1])
        }
      } else {
        context.emit('update:widgetFormSelect', list[index + 1])
      }
      const delObj = list[index]
      if (!isNaN(delObj.model)) {
        // 如果是fieldId是uuid，则默认为新增的字段，不需要记录
        deleteFieldIds.push(delObj.model)
      }
      context.emit('update:widgetForm', {
        ...props.widgetForm,
        list: handleListDelete(list[index].key, oldList),
        deleteFieldIds
      })
    }

    // 拖拽组件
    const handleMoveAdd = (event: any) => {
      const { newIndex } = event

      const key = v4().replaceAll('-', '')
      const list = cloneDeep(props.widgetForm.list)

      list[newIndex] = {
        ...list[newIndex],
        key,
        model: `${key}`,
        rules: []
      }

      if (list[newIndex].type === 'radio' || list[newIndex].type === 'checkbox' || list[newIndex].type === 'select') {
        list[newIndex] = {
          ...list[newIndex],
          options: {
            ...list[newIndex].options,
            options: list[newIndex].options.options.map((item: any) => ({
              ...item
            }))
          }
        }
      }
      if (list[newIndex].type === 'grid') {
        list[newIndex] = {
          ...list[newIndex],
          columns: [[...list[newIndex].columns[0].map((item: any) => ({ ...item }))]]
        }
      }
      context.emit('update:widgetForm', { ...props.widgetForm, list })
      context.emit('update:widgetFormSelect', list[newIndex])
    }

    // 循环事件拖拽组件
    const handleColMoveAdd = (event: any, row: any, index: string | number | symbol) => {
      const { newIndex, oldIndex, item } = event
      const list = cloneDeep(props.widgetForm.list)

      if (item.className.includes('data-grid')) {
        item.tagName === 'DIV' && list.splice(oldIndex, 0, row.columns[0][index].list[newIndex])
        row.columns[0][index].list.splice(newIndex, 1)
        return false
      }

      const key = v4().replaceAll('-', '')

      row.columns[0][index].list[newIndex] = {
        ...row.columns[0][index].list[newIndex],
        key,
        parentKey: row.key,
        model: `${key}`,
        defaultKey: key,
        rules: []
      }

      if (
        row.columns[0][index].list[newIndex].type === 'radio' ||
        row.columns[0][index].list[newIndex].type === 'checkbox' ||
        row.columns[0][index].list[newIndex].type === 'select'
      ) {
        row.columns[0][index].list[newIndex] = {
          ...row.columns[0][index].list[newIndex],
          options: {
            ...row.columns[0][index].list[newIndex].options,
            options: row.columns[0][index].list[newIndex].options.options.map((item: any) => ({ ...item }))
          }
        }
      }

      context.emit('update:widgetFormSelect', row.columns[0][index].list[newIndex])
    }

    return {
      handleItemClick,
      handleCopyClick,
      handleDeleteClick,
      handleMoveAdd,
      handleColMoveAdd
    }
  }
})
</script>
